package ltg.ibutton.hydroroom.gui.tablet;

import java.sql.*;
import java.util.Calendar;
import java.util.Hashtable;

import javax.swing.table.*;

import ltg.ibutton.hydroroom.HydroRoomPersistence;

/**
 * Defines the properties of the JTable rendered in the TabletGui interface
 */
class TableDataModel extends DefaultTableModel {
    
	private static final long serialVersionUID = 1L;
	
	public TableDataModel() {
		// Get the column names and set header names
        addColumn("what");
        addColumn("when");
        addColumn("where");
	}
	
	/**
	 * Sets the table data as the resultset gathered from the database
	 * @param results
	 */
	public void setResultSet(ResultSet results) {
		this.setRowCount(0);
        try {
            ResultSetMetaData metadata = results.getMetaData();
            int columns =  metadata.getColumnCount()-2;
            
            Hashtable<String, Float> classroom = HydroRoomPersistence.getClassroomConf();
    		float mpbw = classroom.get("width")/classroom.get("xblocks");
    		float mpbh = classroom.get("height")/classroom.get("yblocks");
            
            // Get all rows
            while(results.next()) {
                String[] rowData = new String[columns];    // Create array to hold the data
                if(results.getString("type").equals("D")) { //column0 is the type D/S
                	String info = results.getString("info"); //last column retrieved from DB
                	String color = info.substring(info.indexOf("=")+1);
                	rowData[0] = "Dye Tracer ("+color+")";
                }
                else if(results.getString("type").equals("S"))
                	rowData[0] = "Water Sample";
                
                Calendar t = Calendar.getInstance();
                t.setTime(results.getTimestamp("timestamp")); // retrieve the timestamp item
                rowData[1] = (t.get(Calendar.MONTH)+1)+"/"+
                	t.get(Calendar.DAY_OF_MONTH)+"/"+
                	t.get(Calendar.YEAR)+", "+
                	(((t.get(Calendar.HOUR_OF_DAY)==12)?"12":t.get(Calendar.HOUR_OF_DAY)%12))+":"+
                	((t.get(Calendar.MINUTE)>9)?t.get(Calendar.MINUTE):("0"+t.get(Calendar.MINUTE)))+((t.get(Calendar.HOUR_OF_DAY)>=12)?"pm":"am");
                rowData[2] = String.valueOf((char) ((int) (Math.ceil(results.getFloat("x")/mpbw))-1 + (int) 'A')) + "x" + (int) (Math.ceil(results.getFloat("y")/mpbh));
                addRow(rowData);    // Add a row
            }
            
            if(this.getRowCount() < 45)
            	this.setRowCount(45); //fill in the table with some empty rows
            
            fireTableChanged(null);           // Signal the table there is new model data
        } catch (SQLException sqle) {
            System.err.println(sqle.getMessage());
        }
    }
	
	/** 
	 * Sets the table cells as NOT editable since by default they would be
	 */
	public boolean isCellEditable(int row, int col) {
		return false;
    }

}